<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Queue\Capsule\Manager;
use Session;
use DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Log;
use App\ExchangeCode;
use App\BankShop;
use App\Coupon;
use Illuminate\Support\Facades\Auth;

class ExchangeCodeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

	public function index(Request $request) {
		// 查看当前菜单可使用的功能按钮
		$uri = $request->path();
		$data['optionArr'] =  $this->checkMenuOption($uri);
		/**
		 *  判断当前登录账号，如果是第三方网点公司账号，则查询显示当前网点的数据
		 *  如果不是，则默认显示所有
		 */
		$adminUser = Auth::user();
		$phone = $adminUser->name;
		$bank_id = BankShop::getIdByPhone($phone);
		if($bank_id){
			$exchangeCodeObj = ExchangeCode::where('is_del',1)->where('bank_show_id',$bank_id)->get();
		}else{
			$exchangeCodeObj = ExchangeCode::where('is_del',1)->get();
		}

//		dd($exchangeCodeObj);
		$data['exchangeCodes'] = $exchangeCodeObj;

		return view('exchange_code.list')->with($data);
	}

    public function create()
    {
	    // 获取网点列表
	    $data['bankShop'] = BankShop::getAllBankShopId();

        return view('exchange_code.create')->with($data);
    }


    public function store(Request $request){
		$numCode = $request->exchangCodeNum;
		$bank_show_id = $request->bank_show_id;
	    $bank_show_name =DB::table('bank_show')->where('id',$bank_show_id)->pluck('shopName');

	    DB::beginTransaction();
    	if($numCode >1){
			for($i=0;$i<$numCode;$i++){
				$exchangeCodeObj = new ExchangeCode();
				$exchangeCodeObj->bank_show_id =$bank_show_id;
				$exchangeCodeObj->bank_show_name =$bank_show_name[0];
				// 生成兑换码后，检查生成的兑换码是否存在，存在则重新生成
				$exchange_code = $this->exchangCodeCreate();
//				if($this->checkExchangeCodeExist($exchange_code)){
//					$exchange_code = $this->exchangCodeCreate();
//				};

				$exchangeCodeObj->exchange_code =$exchange_code;
				$exchangeCodeObj->code_dec =$request->code_dec;

				if($request->validity){
					if(strpos($request->validity,' - ')){
						$validityArr = explode(' - ',$request->validity);
						$exchangeCodeObj->startTime = $validityArr[0];
						$exchangeCodeObj->endTime = $validityArr[1];
					}else{
						$exchangeCodeObj->validity = $request->validity;
					}
				}
				$exchangeCodeObj->author =Auth::user()->name;
				$exchangeCodeObj->remark =$request->remark;
				$exchangeCodeObj->state =1;
				$exchangeCodeObj->is_del =1;
				if(!$exchangeCodeObj->save()){
					DB::rollback();
					return redirect()->back()->withInput();
				}
			}
	    }else{
		    $exchangeCodeObj = new ExchangeCode();
		    $exchangeCodeObj->bank_show_id =$bank_show_id;
		    $exchangeCodeObj->bank_show_name =$bank_show_name[0];
		    $exchange_code = $this->exchangCodeCreate();
		    // 检查兑换码是否存在，存在则重新生成
//		    if($this->checkExchangeCodeExist($exchange_code)){
//			    $exchange_code = $this->exchangCodeCreate();
//		    };

		    $exchangeCodeObj->exchange_code =$exchange_code;
		    $exchangeCodeObj->code_dec =$request->code_dec;

		    if($request->validity){
			    if(strpos($request->validity,' - ')){
				    $validityArr = explode(' - ',$request->validity);
				    $exchangeCodeObj->startTime = $validityArr[0];
				    $exchangeCodeObj->endTime = $validityArr[1];
			    }else{
				    $exchangeCodeObj->validity = $request->validity;
			    }
		    }
		    $exchangeCodeObj->author =Auth::user()->name;
		    $exchangeCodeObj->remark =$request->remark;
		    $exchangeCodeObj->state =1;
		    $exchangeCodeObj->is_del =1;
		    if(!$exchangeCodeObj->save()){
			    DB::rollback();
			    return redirect()->back()->withInput();
		    }
	    }

	    // 检查该网点是否有优惠券，如果没有新增
	    $exchangeCodeObj = Coupon::where('bank_show_id',$bank_show_id)->count();;
	    if(!$exchangeCodeObj){
		    // 新增优惠券
		    $coupons = new coupon();
		    $coupons->bank_show_id =$bank_show_id;
		    $coupons->bank_show_name =$bank_show_name[0];
		    $coupons->activity_id =3;
		    $coupons->name ='0元免费洗车券';
		    $coupons->cDesc ='与加油站合作满200送“0元免费洗车券”';
		    $coupons->cType = 4; // 现金券
		    $coupons->cType_name ='免费券';
		    $coupons->money =10;
		    $coupons->validity = 36;
		    $coupons->save();
	    }
	    DB::commit();


	    $adminUser = Auth::user();
	    if($adminUser){
		    $userId = $adminUser->id;
		    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').' 新增了兑换码';
		    adminOperationLog($request,$userId,$logs);
	    }
	    return redirect('exchangeCode/list')->with('success','新增成功');

    }


    public function edit($id)
    {
	    $exchangeCodeObj = ExchangeCode::find($id);
	    $data['exchangeCodeInfo'] = $exchangeCodeObj;
	    $data['bankShop'] = BankShop::getAllBankShopId();

//        dd($data['bankShop']);

        return view('exchange_code.edit')->with($data);

    }


    public function update(Request $request, $id){

	    $exchangeCodeObj = ExchangeCode::find($id);
	    $exchangeCodeObj->bank_show_id =$request->bank_show_id;
	    $bank_show_name =DB::table('bank_show')->where('id',$request->bank_show_id)->pluck('shopName');
	    $exchangeCodeObj->bank_show_name =$bank_show_name[0];

	    $exchangeCodeObj->code_dec =$request->code_dec;
//		dd($request->validity);
	    if($request->validity){
		    if(strpos($request->validity,' - ')){
			    $validityArr = explode(' - ',$request->validity);
			    $exchangeCodeObj->startTime = $validityArr[0];
			    $exchangeCodeObj->endTime = $validityArr[1];
			    $exchangeCodeObj->validity = 0;
		    }else{
			    $exchangeCodeObj->validity = $request->validity;
			    $exchangeCodeObj->startTime = NULL;
			    $exchangeCodeObj->endTime = NULL;
		    }
	    }
	    $exchangeCodeObj->author =Auth::user()->name;
	    $exchangeCodeObj->remark =$request->remark;

        if(!$exchangeCodeObj->save()){
            return Redirect::back()->withInput()->withErrors(['fail' => trans('message.updateFail')]);
        }

	    $adminUser = Auth::user();
	    if($adminUser){
		    $userId = $adminUser->id;
		    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'编辑了兑换码：【 '.$exchangeCodeObj->exchange_code.' 】';
		    adminOperationLog($request,$userId,$logs);
	    }

        return Redirect::to(url('exchangeCode/list'))->with('success', trans('message.updateSuccess'));

    }

    // 生成随机兑换码
    public function exchangCodeCreate(){
		$code = $this->createExchangeCode();
	    if($this->checkExchangeCodeExist($code)){
		    $code = $this->createExchangeCode();
	    };

	    return  $code;
    }

    public function createExchangeCode()
    {
	    $len = 6;
	    $chars='0123456789';
//	    mt_srand((double)microtime()*1000000*getmypid());
	    $code="";
	    while(strlen($code)<$len)
		    $code.=substr($chars,(mt_rand()%strlen($chars)),1);
	    return  $code;
    }

	public function checkExchangeCodeExist($code){
	    $exchange_code = [];
	    $exchangeCodeObj = ExchangeCode::where('is_del',1)->select(['exchange_code'])->get();
	    foreach ($exchangeCodeObj as $key=>$value){
		    $exchange_code[] = $value->exchange_code;
	    }

	    if(!in_array($code,$exchange_code)){
		    return  -1;
	    }
	    return  1;
    }

	public function delete(Request $request){

		$bid = $request->id;
		if(!$bid)return -1;
		if(!ExchangeCode::where('id',$bid)->update(['is_del'=>-1])) return -1;

		$adminUser = Auth::user();
		if($adminUser){
			$exchange_code = ExchangeCode::getNameById($bid);
			$userId = $adminUser->id;
			$logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'删除了兑换码：【 '.$exchange_code.' 】';
			adminOperationLog($request,$userId,$logs);
		}
		return 1;
	}



}





